package io.renren.modules.app.service.impl;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import io.renren.common.exception.RRException;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;
import io.renren.common.validator.Assert;
import io.renren.modules.app.dao.UserDao;
import io.renren.modules.app.entity.UserEntity;
import io.renren.modules.app.form.LoginForm;
import io.renren.modules.app.service.UserService;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Map;


@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserDao, UserEntity> implements UserService {

	@Override
	public UserEntity queryByMobile(String mobile) {
		UserEntity userEntity = new UserEntity();
		userEntity.setMobile(mobile);
		return baseMapper.selectOne(userEntity);
	}

	@Override
	public long login(LoginForm form) {
		UserEntity user = queryByMobile(form.getMobile());
		Assert.isNull(user, "手机号或密码错误");

		//密码错误
		if(!user.getPassword().equals(DigestUtils.sha256Hex(form.getPassword()))){
			throw new RRException("手机号或密码错误");
		}

		return user.getUserId();
	}

	@Override
	public PageUtils queryPage(Map<String, Object> params) {
		String username = (String) params.get("username");
		Page<UserEntity> page = this.selectPage(
				new Query<UserEntity>(params).getPage(),
				new EntityWrapper<UserEntity>()
						.like(StringUtils.isNotBlank(username),"username",username)
		);
		return new PageUtils(page);
	}

	@Override
	public UserEntity queryByUserId(Long userId) {

		UserEntity userEntity = new UserEntity();
		userEntity.setUserId(userId);
		return baseMapper.selectOne(userEntity);

	}

	@Override
	public boolean updateUser(UserEntity userEntity) {

		Integer res = baseMapper.update(userEntity, new EntityWrapper<UserEntity>()
				.where("user_id={0}",userEntity.getUserId()));

		return res != null && res > 0;
	}
}
